package cn.yinuo.website.common.web;

import cn.yinuo.website.common.ResultVO;
import cn.yinuo.website.common.exception.BusinessRuntimeException;
import cn.yinuo.website.common.security.JavaWebToken;
import cn.yinuo.website.user.entity.User;
import cn.yinuo.website.user.service.IUserService;
import com.google.common.base.Strings;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController("/auth")
@Api("认证")
public class AuthController {
    
    @Autowired
    IUserService userService;
    @Autowired
    JavaWebToken javaWebToken;
    @PostMapping("/login")
    @ApiOperation("登陆")
    public String doLogin(@RequestBody User userVo, HttpServletRequest request) {
        if (Objects.isNull(userVo) || Strings.isNullOrEmpty(userVo.getSignName())
                || Strings.isNullOrEmpty(userVo.getPassword()))
            throw new BusinessRuntimeException( "用户名或密码不能为空" );
        if (org.apache.commons.lang3.StringUtils.containsWhitespace(userVo.getSignName()) || org.apache.commons.lang3.StringUtils.containsWhitespace(userVo.getPassword())) {
            throw new BusinessRuntimeException( "用户名或密码不能包含空格" );
        }
        userVo.setSignName(StringUtils.trim(userVo.getSignName())).setPassword(StringUtils.trim(userVo.getPassword()));
        ResultVO<String> result = new ResultVO<String>();
        User vo = userService.getBySignName(userVo.getSignName());
        if (Objects.isNull( vo ))
            throw new BusinessRuntimeException( "用户名或密码不正确" );
        if (!new BCryptPasswordEncoder().matches(userVo.getPassword(),vo.getPassword())) {
            throw new BusinessRuntimeException("用户名或密码不正确");
        }
        // 设置token
        String token = javaWebToken.createJwt(vo);
        return token;
    }
}
